package com.csaba.util;

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggerHelper
{
	private final static Logger logger = getDefaultLogger();

	public static Logger getDefaultLogger()
	{
		final Exception e = new Exception();
		final StackTraceElement[] ste = e.getStackTrace();
		String packageName = "";
		if ( ste.length > 1 )
		{
			packageName = ste[1].getClassName();
			packageName = packageName.substring(0, packageName.lastIndexOf('.'));
		}
		return Logger.getLogger(packageName);
	}

	public static void initLogger()
	{
		initLogger(Level.FINE);
	}

	private static Logger getRootLogger()
	{
		Logger parent = logger.getParent();
		if ( parent == null )
		{
			parent = logger;
		}
		else
		{
			while ( parent.getParent() != null )
				parent = parent.getParent();
		}
		return parent;
	}

	public static void initLogger( final Level level )
	{
		setLogLevel(level);
		setConsoleLogging();
		logger.fine("Logger inicialized...");
	}

	public static void setFileLogging()
	{
		final Logger root = getRootLogger();

		FileHandler fileHandler;
		try
		{
			fileHandler = new FileHandler("sbt", true);
			fileHandler.setLevel(Level.ALL);
			fileHandler.setFormatter(new OneLineFormatter());
		}
		catch ( final Exception ex )
		{
			logger.log(Level.SEVERE, "Error initializing file logging.", ex);
			return;
		}

		final Handler[] hs = root.getHandlers();
		for ( int i = 0; i < hs.length; i++ )
		{
			root.removeHandler(hs[i]);
		}

		root.addHandler(fileHandler);
	}

	public static void setConsoleLogging()
	{
		final Logger root = getRootLogger();

		final Handler[] hs = root.getHandlers();
		for ( int i = 0; i < hs.length; i++ )
		{
			root.removeHandler(hs[i]);
		}

		final ConsoleHandler ch = new ConsoleHandler();
		ch.setLevel(Level.ALL);
		ch.setFormatter(new OneLineFormatter());
		root.addHandler(ch);
	}

	public static void setLogLevel( final Level level )
	{
		final Logger root = getRootLogger();
		if ( level.intValue() < Level.WARNING.intValue() )
		{
			root.setLevel(Level.WARNING);
		}
		else
		{
			root.setLevel(level);
		}

		final Logger comCsabaLogger = Logger.getLogger("com.csaba");
		comCsabaLogger.setLevel(level);

		logger.fine("Log level set to:" + level);
	}
}
